
import styled from 'styled-components';
import React, { CSSProperties, useState, useEffect } from 'react';
import { Card, Button, Radio, Tabs, Space, Input } from 'antd';
import { PlusOutlined, OrderedListOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import type { TabsProps } from 'antd';

import { CategoryList } from '../../../../components';

import { DataSource, metaDataGetMetaDataObjects, MetaDataObject, DataSourceDomainMappingObject, dataSourceDomainGetMappingObjectByObjIdentifier, dataSourceDomainSaveMappingObject } from '../../../../services';
import { dsFind, dsFindOne, dsInsert, dsUpdate, dsUpdateById, ComparsionOperator } from '@/services/local';
import { CLASS_CLASS_IDENTIFIER, DATASOURCE_CLASS_MAPPINGS_CLASS_IDENTIFIER} from '@/services/constants';

export interface DataValuesDomainMappingPanelProps {
    style?: CSSProperties;
    dataSource: DataSource;
    domainIdentifier: string;
    onDomainChange?: (domainIdentifier: string) => Promise<void>;
}

export const DataValuesDomainMappingPanel: React.FC<DataValuesDomainMappingPanelProps> = (props) => {

    const [objects, setObjects] = useState<MetaDataObject[]>([]);

    const [activeKey, setActiveKey] = useState<string | null>(null);

    const [mappingObject, setMappingObject] = useState<DataSourceDomainMappingObject>({
        id: 0,
        datasource_id: props.dataSource.id,
        domain_identifier: props.domainIdentifier,
        class_identifier: '',
        mapping_type: 'sql',
        mapping_value: '',
        table_name: '',
        options: '',
        description: ''
    });

    useEffect(() => {
        //props.domainIdentifier
        dsFind(0, CLASS_CLASS_IDENTIFIER, {
            attributes: [{
                name: 'domain_identifier',
                operator: ComparsionOperator.Equal,
                value: props.domainIdentifier
            }]
        }).then((res) => {
            console.log(res);
            setObjects(res.data);
        }).catch((err) => {
            console.error(err);
        });
    }, [props.domainIdentifier]);

    useEffect(() => {
        if (!activeKey || activeKey === '') {
            return;
        }
        //props.dataSource.id
        dsFindOne(0, DATASOURCE_CLASS_MAPPINGS_CLASS_IDENTIFIER, {
            attributes: [
                {
                    name: 'datasource_id',
                    operator: ComparsionOperator.Equal,
                    value: props.dataSource.id + ''
                },
                {
                    name: 'class_identifier',
                    operator: ComparsionOperator.Equal,
                    value: activeKey
                }
            ]
        }).then((objMapping) => {
            console.log(objMapping);
            if (objMapping == null) {
                setMappingObject({
                    id: 0,
                    datasource_id: props.dataSource.id,
                    domain_identifier: props.domainIdentifier,
                    class_identifier: activeKey,
                    mapping_type: 'sql',
                    mapping_value: '',
                    table_name: '',
                    options: '',
                    description: ''
                });
                return;
            }
            setMappingObject(objMapping);
        }).catch((err) => {
            console.error(err);
            setMappingObject({
                id: 0,
                datasource_id: props.dataSource.id,
                domain_identifier: props.domainIdentifier,
                class_identifier: activeKey,
                mapping_type: 'sql',
                mapping_value: '',
                table_name: '',
                options: '',
                description: ''
            });
        });
    }, [props.dataSource, activeKey]);

    return (
        <Container style={props.style}>
            <StyledCard
                style={{
                    width: '220px'
                }}
                title={'对象列表'}
                styles={{
                    body: {
                        padding: '0px 2px',
                        overflow: 'auto',
                        height: 'calc(100% - 40px)'
                    }
                }}
            >
                <CategoryList
                    style={{}}
                    items={objects.map((item, index) => {
                        return {
                            label: item.name,
                            key: item.identifier,
                            icon: <OrderedListOutlined />,
                        };
                    })}
                    activeKey={activeKey}
                    onChange={async (key, item) => {
                        setActiveKey(key);
                    }}
                    filter={false}
                ></CategoryList>
            </StyledCard>
            <StyledCard
                style={{
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                }}
                title={'数据映射'}
                styles={{
                    body: {
                        padding: '6px 6px'
                    }
                }}
            >
                {
                    activeKey ?
                        <>
                            <Space style={{ margin: '6px', display: 'flex', justifyContent: 'space-between' }}>
                                <Radio.Group onChange={(event: RadioChangeEvent) => {
                                    setMappingObject({ ...mappingObject, mapping_type: event.target.value });
                                }} value={mappingObject ? mappingObject.mapping_type : 'table'}>
                                    <Radio value={'table'}>单表映射</Radio>
                                    <Radio value={'sql'}>SQL映射</Radio>
                                </Radio.Group>
                                <Space>
                                    <Button style={{
                                    }} size={'small'} onClick={async () => {
                                        dataSourceDomainGetMappingObjectByObjIdentifier(props.dataSource.id, activeKey).then((objMapping) => {
                                            if (objMapping == null) {
                                                setMappingObject({
                                                    id: 0,
                                                    datasource_id: props.dataSource.id,
                                                    domain_identifier: props.domainIdentifier,
                                                    class_identifier: activeKey,
                                                    mapping_type: 'sql',
                                                    mapping_value: '',
                                                    table_name: '',
                                                    options: '',
                                                    description: ''
                                                });
                                                return;
                                            }
                                            setMappingObject(objMapping);
                                        }).catch((err) => {
                                            console.error(err);
                                        });
                                    }}>重置</Button>
                                    <Button style={{
                                    }} type={'dashed'} danger size={'small'} onClick={async () => {
                                        if (mappingObject.id > 0) {
                                            dsUpdateById(0, DATASOURCE_CLASS_MAPPINGS_CLASS_IDENTIFIER, mappingObject.id, mappingObject);
                                        } else {
                                            let res = await dsInsert(0, DATASOURCE_CLASS_MAPPINGS_CLASS_IDENTIFIER, mappingObject);
                                            console.log(res);
                                            if (res > 0) {
                                                setMappingObject({ ...mappingObject, id: res });
                                            }
                                        }


                                    }}>保存</Button>
                                </Space>
                            </Space>
                            <FormContainer
                                style={{
                                    display: (mappingObject ? mappingObject.mapping_type : 'table') !== 'table' ? 'none' : undefined
                                }}
                            >
                                <Input value={mappingObject ? mappingObject.table_name : ''} onChange={(event) => {
                                    setMappingObject({ ...mappingObject, table_name: event.target.value });
                                }}></Input>
                            </FormContainer>
                            <FormContainer
                                style={{
                                    display: (mappingObject ? mappingObject.mapping_type : 'table') !== 'sql' ? 'none' : undefined
                                }}
                            >
                                <Input.TextArea
                                    rows={9}
                                    value={mappingObject ? mappingObject.mapping_value : ''}
                                    onChange={(event) => {
                                        setMappingObject({ ...mappingObject, mapping_value: event.target.value });
                                    }}></Input.TextArea>
                            </FormContainer>
                        </>
                        : (
                            <Space style={{ margin: '6px' }}>
                                请选择对象！
                            </Space>
                        )
                }
            </StyledCard>
        </Container>
    );
}

const Container = styled.div`
    flex:  1;
    width: 100%;
    overflow: hidden;
    padding: 6px 6px;
    display: flex;
    gap: 6px;
`;

const StyledCard = styled(Card)`
`

const FormContainer = styled.div`
    flex:  1;
    width: 100%;
    min-height: 200px;
`;